package com.wfit.controller.app;

import com.google.code.kaptcha.Producer;
import com.wfit.constant.AppUserCodeConstant;
import com.wfit.context.UserContext;
import com.wfit.dto.AppUsersDto;
import com.wfit.mapper.AppUsersMapper;
import com.wfit.po.AppUsers;
import com.wfit.po.Users;
import com.wfit.result.Result;
import com.wfit.service.AppUsersService;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.time.Duration;
import java.util.HashMap;

@RestController
@RequestMapping("/app/users")

public class AppUserController {

    @Autowired
    private Producer captchaProducer;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private AppUsersService appUsersMapper;

    @GetMapping("/image/{phone}")
    public void getCaptchaImage(HttpServletResponse response, @PathVariable String phone) throws IOException {
        // 设置响应头
        response.setHeader("Cache-Control", "no-store, no-cache");
        response.setContentType("image/jpeg");

        // 生成验证码文本
        String text = captchaProducer.createText();

        // 生成验证码图片
        BufferedImage image = captchaProducer.createImage(text);

        // 将验证码文本存入session或缓存
        // 这里假设使用session存储
        // request.getSession().setAttribute("captcha", text);

        Object o = redisTemplate.opsForValue().get(AppUserCodeConstant.LOGIN_CODE + phone);
        if ( o != null ) {
            redisTemplate.delete(AppUserCodeConstant.LOGIN_CODE + phone);
        }
            redisTemplate.opsForValue().set(AppUserCodeConstant.LOGIN_CODE + phone, text);


        // 将图片写入响应流
        ServletOutputStream out = response.getOutputStream();
        ImageIO.write(image, "jpg", out);
        out.flush();
        out.close();
    }

    @PostMapping("/login")
    public Result login(@RequestBody AppUsersDto dto) {
        Result result = appUsersMapper.login(dto);
        return result;
    }


    @GetMapping("/userinfo")
    public Result getUserInfo(){
        Long user = UserContext.getUser();
        AppUsers userInfo = appUsersMapper.getById(user);
        return Result.success(userInfo);
    }
}
